/*
 * @(#)GetCookieDirective.java $version 2010. 8. 11
 *
 * Copyright 2007-2010 NHN Corp. All rights Reserved. 
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.nhncorp.usf.core.result.template.directive;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.nhncorp.usf.core.Constants;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 원하는 Cookie 값을 지정된 변수명으로 저장하는 {@link TemplateDirective}.
 *
 * @author Web Platform Development Team
 */
public class GetCookieDirective extends AbstractTemplateDirectiveModel {
    @SuppressWarnings("unchecked")
	private Map usfDataModel;

    /**
     * Instantiates a new gets the cookie directive.
     *
     * @param dataModel the data model
     */
    @SuppressWarnings("unchecked")
	public GetCookieDirective(Map dataModel) {
        usfDataModel = dataModel;
    }

    /**
     * 원하는 쿠키이름 (params : key) 으로 쿠키를 찾아 변수 (params : returned) 로 저장.
     *
     * @param env      Environment
     * @param loopVars TemplateModel
     * @param body     TemplateDirectiveBody
     * @param params   Map
     * @throws TemplateException the TemplateException
     * @throws IOException       the IOException
     */
    @SuppressWarnings("unchecked")
	public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        String key = getAsString(params.get("key"));
        String returnId = getAsString(params.get("returnid"));

        if (key == null || returnId == null) {
            log.debug("illegal arguement. Parameter [key] or [returnid] is empty");
            return;
        }

        HttpServletRequest request = (HttpServletRequest)usfDataModel.get(Constants.FREEMARKER_KEY_REQUEST);
        Cookie[] cookies = request.getCookies();

        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (key.equals(cookie.getName())) {
                    env.setVariable(returnId, env.getObjectWrapper().wrap(cookie.getValue()));
                }
            }
        }
    }
}
